#include<stdio.h>
#include<signal.h>
#include<time.h>
#include<sys/ipc.h>
#include<stdlib.h>
#include<ctype.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<string.h>

// void interrupt(int signo)
// {
//     printf("interrrupt called!\n");
//     sleep(3);
//     printf("interrupt Func Ended.\n");

// }
// int main()
// {
//     signal(SIGINT,interrupt);
//     printf("Interrupt set for SIGINT\n");
//     sleep(10);
//     printf("Program NORMAL ended.\n");
//     return;

// }
#define MAX_SEND_SIZE 80
struct my_msgbuf
{
    long mtype;
    char mtext[MAX_SEND_SIZE];
};

void send_message(int qid,struct my_msgbuf* mbuf,long type,char test);
void read_message(int qid,struct my_msgbuf* mbuf,long type);
void remove_queue(int qid);
void change_queue_mode(int qid,char* mode);
void usage(void);

void send_message(int qid,struct my_msgbuf* mbuf,long type,char* text)
{
    printf("send message!...\n");
    mbuf->mtype=type;
    strcpy(mbuf->mtext,text);
    if(msgsnd(qid,(struct msgbuf*)mbuf,strlen(mbuf->mtext)+1,0))
    {
        perror("msgsnd!");

    }

}
void read_message(int qid,struct my_msgbuf* mbuf,long type)
{
    printf("read message!...\n");
    mbuf->mtype=type;
    msgrcv(qid,(struct msgbuf*)mbuf,MAX_SEND_SIZE,type,0);
    printf("type:%ld,Text:%s",type,mbuf->mtext);
}
void remove_queue(int qid)
{
    msgctl(qid,IPC_RMID,0);
}
//啊帮助信息
void usage(void)
{
    fprintf(stderr,"用法:msgtool,[s|r|d] [参数]\n");
    fprintf(stderr, "  s <类型> <内容>  发送消息（类型为正整数）\n");
    fprintf(stderr, "  r <类型>         读取指定类型的消息\n");
    fprintf(stderr, "  d                删除消息队列\n");
}

int main(int argc ,char* argv[])
{
    key_t key;
    int message_id;
    struct my_msgbuf mbuf;
    if(argc==1)
    {
        usage();
    }
    key=ftok(".",'m');
    if(message_id=msgget(key,IPC_CREAT|0666)==-1)
    {
        perror("msgget");
        exit(1);
    }
    switch(tolower(argv[1][0]))
    {
        case 's':
            send_message(message_id,&mbuf,atoi(argv[2]),argv[3]);
            break;
        case 'r':
            read_message(message_id,&mbuf,atoi(argv[2]));
            break;
        case 'd':
            remove_queue(message_id);
            break;
        default:
            usage();
            break;
        
    }
    return 0;
}